<template>
  <div class="news-addEdit">
    <!-- 添加编辑左边数据 -->
    <el-dialog :append-to-body="true" width="80%" :title="title" v-model="show" @close="cancelFun" destroy-on-close>
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="文章封面图: ( 1920x670 )" prop="img" style="height: auto">
          <el-upload
            :http-request="upload"
            action=""
            list-type="picture-card"
            :on-preview="imgPreview"
            :on-remove="imgRemove"
            :file-list="form.img"
            accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.GIF"
            :limit="1"
            :on-exceed="limitFun"
            :disabled="disabled"
            :class="{ hide: hideUpload }"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章标题:" prop="title">
          <el-input type="text" placeholder="请输入内容" size="large" v-model="form.title" maxlength="50" :disabled="disabled" show-word-limit> </el-input>
        </el-form-item>
        <el-form-item label="文章内容:" prop="html" v-if="!disabled">
          <CustomEditor :default-content="form.content" height="300px" :textNum="50" @content-change="contentChange"></CustomEditor>
        </el-form-item>
        <el-form-item label="文章内容:" v-if="disabled">
          <div v-html="form.html"></div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelFun" size="large">取消</el-button>
          <el-button type="primary" @click="confirmFun" size="large" v-if="!disabled">确认</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 图片预览 -->
    <el-dialog :append-to-body="true" v-model="showImages">
      <img style="width: 100%" :src="imageUrl" alt="" />
    </el-dialog>
  </div>
</template>
<script setup>
import CustomEditor from '@components/common/CustomEditor/main.vue'
import { computed, onMounted, onUnmounted, ref, watch, defineEmits, reactive } from 'vue'
import { formatHtml } from '@utils/formatHtml'
import { uploadFile } from '@utils/obs.js'
import { ElMessage } from 'element-plus'
import News from '@api/news/index'

const props = defineProps({
  typeId: {
    type: String,
    default: null
  },
  status: {
    type: String,
    default: null
  },
  show: {
    type: Boolean,
    default: null
  },
  addEditData: {
    type: Object,
    default: {
      id: '',
      title: '',
      img: [],
      content: '[]',
      html: '',
      abstracts: ''
    }
  }
})

// *********************************************表单
const formRef = ref()

const form = reactive({
  id: '',
  title: '',
  img: [],
  content: '[]',
  html: '',
  abstracts: ''
})

const rules = reactive({
  title: [{ required: true, message: '文章标题不能为空!', trigger: 'blur' }],
  img: [
    {
      required: true,
      validator: (rule, value, callback) => {
        value = form.img
        if (!value || !value.length) {
          callback(new Error('文章封面图不能为空!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  html: [
    {
      required: true,
      validator: (rule, value, callback) => {
        value = form.html
        if (!value || value === '<p><br></p>' || value === '<p></p>') {
          callback(new Error('文章内容不能为空!'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const emit = defineEmits(['change-addEdit'])

const defaultContent = ref()

const contentChange = (content, html, text) => {
  form.content = content
  form.html = html
  form.abstracts = text
  console.log(html)
  // formRef.value.validateField(['html'], async (valid) => {})
  formRef.value.validateField(['html'], async (valid) => {})
}

let statusMap = { add: '添加文章', edit: '编辑文章', read: '查看文章' }
const title = computed(() => {
  return statusMap[props.status]
})

const disabled = computed(() => {
  return props.status == 'read' ? true : false
})

function confirmFun() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      form.html = formatHtml(form.html)

      let { id, abstracts, title, img, content, html } = form
      img = img.length ? img.map((v) => v.url).join(',') : ''

      let data = {
        title,
        abstracts,
        newsCover: img,
        news: html,
        content,
        typeCode: props.typeId
      }
      let res = ''

      if (props.status == 'add') {
        data.status = '2'
        res = await new News().add(data)
      } else {
        data.id = id
        res = await new News().edit(data)
      }

      if (res.code == 200) {
        ElMessage({
          message: `${props.status == 'add' ? '新增成功!' : '更新成功!'}`,
          type: 'success'
        })
        emit('change-addEdit', form, props.status)
      }
    }
  })
}

function cancelFun() {
  emit('change-addEdit', form, 'cancel')
}

// *********************************************上传
//图片上传
const showImages = ref(false)
const imageUrl = ref('')

const hideUpload = computed(() => {
  return form.img.length ? true : false
})

//超出限制
function limitFun() {
  ElMessage.error('最多上传1张!')
}
//图片删除
function imgRemove(file, filelist) {
  form.img = []
}
//图片预览
function imgPreview(file) {
  imageUrl.value = file.url
  showImages.value = true
}

function upload(params) {
  let { file } = params

  uploadFile({ file })
    .then((res) => {
      let url = res.url
      if (res.url.indexOf('http') < 0) {
        url = `http://${res.url}`
      }
      form.img = [{ url, name: url }]
      formRef.value.validateField(['img'], async (valid) => {})
    })
    .finally(() => {})
}

watch(
  () => props.show,
  (newValue, oldValue) => {
    let { id, title, img, content, html, abstracts } = props.addEditData
    if (newValue) {
      form.id = id
      form.title = title
      form.img = img
      form.content = content
      form.html = html
      form.abstracts = abstracts
      console.log(props.show)
      console.log(props.addEditData)
    } else {
      form.img = []
    }
  },
  { deep: true }
)
</script>
<style lang="scss">
.news-addEdit {
}
</style>
<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
